package com.cgsd.heyu.http;


import com.android.library.utils.LogUtils;
import com.android.library.utils.SystemUtil;
import com.cgsd.heyu.App;

import io.reactivex.observers.DefaultObserver;

/**
 * @author xiaoxing
 * Created by Administrator on 2018/3/25.
 * 显示进度
 */

public  abstract class RxFileSubscriber<T> extends DefaultObserver<T> {

    @Override
    public void onNext(T value) {
        onSuccess(value);
    }

    @Override
    public void onError(Throwable e) {
        //错误信息打印
        LogUtils.e(LogUtils.DEFAULT_TAG,e.getMessage());
        ExceptionHandler.ResponseThrowableException responseThrowable;
        //接下来可以检查网络连接等操作
        if (!SystemUtil.isNetworkAvailable(App.getInstance())) {
            onError(new ErrorMessage(GlobalErrorMessage.ErrorMessage.ERROR_MESSAGE_1000));
        }else if (e instanceof AnalysisErrorException){
            //解析异常
            AnalysisErrorException analysisErrorException = (AnalysisErrorException) e;
            onError(new ErrorMessage(analysisErrorException.getCode(),analysisErrorException.getMessage()));
        } else if(e instanceof Exception){
            //访问获得对应的Exception
            responseThrowable = ExceptionHandler.handleException(e);
            onError(new ErrorMessage(responseThrowable.code,responseThrowable.message));
        }else {
            //将Throwable 和 未知错误的status code返回
            responseThrowable = new ExceptionHandler.ResponseThrowableException(e,ExceptionHandler.Error.UNKNOWN);
            onError(new ErrorMessage(responseThrowable.code,responseThrowable.message));
        }
    }

    /**
     * 监听进度的改变
     */
    public void onProgressChange(long bytesWritten, long contentLength) {
        onProgress((int) (bytesWritten*100 / contentLength));
    }

    @Override
    public void onComplete() {

    }

    /**
     * 失败
     * @param error
     */
    public abstract void onError(ErrorMessage error);

    /**
     * 成功回调
     * @param t
     */
    public abstract void onSuccess(T t);

    /**
     * 上传进度回调
     * @param progress
     */
    public abstract void onProgress(int progress);

}
